import { Component, OnInit, OnDestroy } from '@angular/core';
import { _HttpClient, ModalHelper, SettingsService } from '@delon/theme';
import { NzNotificationService } from 'ng-zorro-antd';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, debounceTime, switchMap } from 'rxjs/operators';
import { StragegySelectModalComponent } from '../components/strategy/strategy-modal.component';

interface MsgMeta {
  label: string;
  value: any;
  remark: string;
  type: string;
  code: string;
}

/**
 * 消息发送工具
 */
@Component({
  selector: 'msg-sender',
  templateUrl: './msg-sender.component.html',
  styleUrls: ['./msg-sender.component.less'],
})
export class MsgSenderComponent implements OnInit, OnDestroy {
  msgForm: FormGroup;
  url = `/cf/admin/web-msg/meta/page`;
  url2 = `/cf/admin/user/page`;
  searchChange$ = new BehaviorSubject('');
  searchChange2$ = new BehaviorSubject('');
  optionList: MsgMeta[] = [];
  optionList2: any[] = [];
  isLoading = false;
  isLoading2 = false;

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private notice: NzNotificationService,
    private settings: SettingsService,
    private fb: FormBuilder,
  ) {}

  ngOnInit(): void {
    this.msgForm = this.fb.group({
      meta: [null, [Validators.required]],
      recer: [null],
      title: [null, [Validators.required]],
      content: [null, [Validators.required]],
    });

    // tslint:disable:no-any
    const getMsgMetaList = (name: string) =>
      this.http
        .get(`${this.url}`, { msgName: name, isFreeze: '0', current: 1, size: 100 })
        .pipe(map((res: any) => res.data.records))
        .pipe(
          map((list: any) => {
            return list.map((item: any) => {
              return {
                type: `${item.msgType}`,
                label: `${item.msgName}`,
                code: `${item.msgCode}`,
                value: item,
                remark: item.msgRemark,
              };
            });
          }),
        );
    const optionList$: Observable<MsgMeta[]> = this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .pipe(switchMap(getMsgMetaList));
    optionList$.subscribe(data => {
      this.optionList = data;
      this.isLoading = false;
    });

    // tslint:disable:no-any
    const getRandomNameList = (name: string) =>
      this.http
        .get(`${this.url2}`, { keyword: name, current: 1, size: 20 })
        .pipe(map((res: any) => res.data.records))
        .pipe(
          map((list: any) => {
            return list.map((item: any) => {
              return { label: `${item.name}(${item.username})`, value: item.userId };
            });
          }),
        );
    const optionList2$: Observable<any[]> = this.searchChange2$
      .asObservable()
      .pipe(debounceTime(500))
      .pipe(switchMap(getRandomNameList));
    optionList2$.subscribe(data => {
      this.optionList2 = data;
      this.isLoading2 = false;
    });
  }

  ngOnDestroy() {
    this.searchChange$.unsubscribe();
    this.searchChange2$.unsubscribe();
  }

  submitForm(): void {
    Object.keys(this.msgForm.controls).forEach(key => {
      this.msgForm.controls[key].markAsDirty();
      this.msgForm.controls[key].updateValueAndValidity();
    });
    if (this.msgForm.invalid) {
      return;
    }
    const data = this.msgForm.value;
    this.http
      .post(`/cf/admin/web-msg/send`, {
        metaId: data.meta.id,
        isBroadcast: '0',
        title: data.title,
        content: data.content,
        fromerId: this.settings.user.userId,
        fromer: this.settings.user.name,
        receivers: data.recer,
      })
      .subscribe(res => {
        this.notice.success('成功', '消息发送成功');
        this.msgForm.reset();
      });
  }

  onSearch(value: string): void {
    this.isLoading = true;
    this.searchChange$.next(value);
  }

  onSearchRecer(value: string): void {
    this.isLoading2 = true;
    this.searchChange2$.next(value);
  }

  compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.id === o2.id : o1 === o2);

  get metaVal() {
    return this.msgForm.controls.meta.value;
  }

  // 选择消息元数据
  selectMeta(val) {}

  // 查看收信人
  openModal() {
    this.modal
      .open(StragegySelectModalComponent, { record: this.metaVal, title: '收信方', view: true })
      .subscribe(res => {});
  }

  reset() {
    this.msgForm.reset();
  }
}
